package com.yunda.nebula.gateway.service;

import com.alibaba.fastjson.JSONObject;
import com.yunda.nebula.gateway.core.entity.AppInfo;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import com.yunda.nebula.gateway.core.entity.FilterInfo;
import com.yunda.nebula.gateway.core.entity.PathInfo;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.*;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/17 14:36
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Service
public class RouteDefinitionPraseService {

    public RouteDefinition parse(ConfigData configData){
        RouteDefinition routeDefinition = new RouteDefinition();
        routeDefinition.setId(configData.getAppId());
        AppInfo appInfo = configData.getAppInfo();
        URI uri = UriComponentsBuilder.fromUriString(appInfo.getUrl()).build().toUri();
        routeDefinition.setUri(uri);

        PredicateDefinition predicateDefinition = parsePredicateDefinition(configData.getPathInfo());
        routeDefinition.setPredicates(Collections.singletonList(predicateDefinition));

        List<FilterInfo> filterInfos = configData.getFilterInfos();
        List<FilterDefinition> filterDefinitions = new ArrayList<>();
        for (FilterInfo filterInfo:filterInfos){
            FilterDefinition filterDefinition = parseFilterDefinition(filterInfo);
            filterDefinitions.add(filterDefinition);
        }
        routeDefinition.setFilters(filterDefinitions);
        return routeDefinition;
    }


    public PredicateDefinition parsePredicateDefinition(PathInfo pathInfo) {
        PredicateDefinition predicateDefinition = new PredicateDefinition();
        predicateDefinition.setName(pathInfo.getType());
        Map<String, String> predicateParams = new HashMap<>(8);
        predicateParams.put("pattern", pathInfo.getValue());
        predicateDefinition.setArgs(predicateParams);
        return predicateDefinition;
    }

    public FilterDefinition parseFilterDefinition(FilterInfo filterInfo) {
        FilterDefinition predicateDefinition = new FilterDefinition();
        predicateDefinition.setName(filterInfo.getFilterName());
        Map<String, String> filterParams = new HashMap<>(8);
        JSONObject jsonObject = JSONObject.parseObject(filterInfo.getConfig());
        for (String key:jsonObject.keySet()){
            filterParams.put(key,jsonObject.getString(key));
        }
        predicateDefinition.setArgs(filterParams);
        return predicateDefinition;
    }

}
